﻿using Common.Utility;
using DTO;
using DTO.DTO.Com;
using Microsoft.AspNetCore.Mvc;
using System.Collections;
using System.Text;
using Web.Filter;

namespace Web.Controllers
{
    [NoPermission]
    public class UploadController : BaseController
    {
        #region 初始化
        public UploadController()
        {
        }
        #endregion

        #region 图片上传
        public async Task<IActionResult> UeditorUpload()
        {
            var files = Request.Form.Files;
            string callback = Request.Query["callback"];
            string editorId = Request.Query["editorid"];
            if (files != null && files.Count > 0)
            {
                var file = files[0];
                #region 上传文件
                string file_path = "";
                if (file != null)
                {
                    var result = UploadUtils.OSSFileUpload(file, "UMEditor");
                    if (result.Code != 0)
                    {
                        var info = getUploadInfo("", "", "", 0, "", "FAILD");
                        await Response.WriteAsync(BuildJson(info));
                        return new EmptyResult();
                    }
                    file_path = Convert.ToString(result.Data);
                }
                #endregion

                var fileInfo = getUploadInfo(file_path, file.FileName,
                    Path.GetFileName(file_path), file.Length, Path.GetExtension(file.FileName));
                string json = BuildJson(fileInfo);

                Response.ContentType = "text/html";
                if (callback != null)
                {
                    await Response.WriteAsync(String.Format("<script>{0}(JSON.parse(\"{1}\"));</script>", callback, json));
                }
                else
                {
                    await Response.WriteAsync(json);

                }
                return new EmptyResult();
            }
            return new EmptyResult();
        }
        private string BuildJson(Hashtable info)
        {
            List<string> fields = new List<string>();
            string[] keys = new string[] { "originalName", "name", "url", "size", "state", "type" };
            for (int i = 0; i < keys.Length; i++)
            {
                fields.Add(String.Format("\"{0}\": \"{1}\"", keys[i], info[keys[i]]));
            }
            return "{" + String.Join(",", fields) + "}";
        }
        /**
       * 获取上传信息
       * @return Hashtable
       */
        private Hashtable getUploadInfo(string URL, string originalName, string name, long size, string type, string state = "SUCCESS")
        {
            Hashtable infoList = new Hashtable();

            infoList.Add("state", state);
            infoList.Add("url", $"{AppSetting.GetAppSetting("Aliyun:OSS:Url")}{URL}");
            infoList.Add("originalName", originalName);
            infoList.Add("name", name);
            infoList.Add("size", size);
            infoList.Add("type", type);

            return infoList;
        }

        public Result UploadFile()
        {
            var result = UploadUtils.FileUpload(Request.Form.Files[0], AppSetting.GetAppSetting("PhysicalPath"), Request.Form["Folder"]);
            if (result.Code == 0)
            {
                result.Data = SitePath + result.Data;
            }
            return new Result { Code = result.Code, Msg = result.Msg, Data = result.Data };
        }

        public Result GetSTSToken(GetSTSTokenDTO dto)
        {
            var result = OSSHelper.GetSTSToken();
            if (result == null)
            {
                return Result.Failed(-1, "未能获取阿里上传TOKEN");
            }
            string fileName = $"/{dto.Folder}/{DateTime.Now.ToString("yyyyMMdd")}/{GetFileName()}.{dto.Ext}";
            return new Result
            {
                Code = 0,
                Msg = "成功",
                Data = new
                {
                    RegionId = AppSetting.GetAppSetting("Aliyun:OSS:RegionId"),
                    result.AccessKeyId,
                    result.AccessKeySecret,
                    result.SecurityToken,
                    FileName = fileName,
                    BucketName = AppSetting.GetAppSetting("Aliyun:OSS:BucketName"),
                }
            };
        }
        #endregion

        private static string GetFileName()
        {
            Random rd = new Random();
            StringBuilder serial = new StringBuilder();
            serial.Append(DateTime.Now.ToString("yyyyMMddHHmmss"));
            serial.Append(rd.Next(1000, 9999).ToString());
            return serial.ToString();

        }
    }
}